import type { Directive } from 'vue';

/**
 * @description 禁止 ios 橡皮筋效果
 * @author wfd
 * @date 2022/8/24 15:40
 * @example v-scroll-fix
 */
const scrollFix: Directive = {
  mounted(el: Element) {
    let lastTouch: { screenY?: number } = {};

    el.addEventListener('touchstart', (e: TouchEvent) => {
      lastTouch = e.touches[0];
    });

    el.addEventListener(
      'touchmove',
      (e: TouchEvent) => {
        e.stopPropagation();
        const scrollEl = e.currentTarget as HTMLElement,
          touch = e.touches[0];

        // 判定当前滚动容器是否可以滚动
        if (
          scrollEl.scrollHeight <= scrollEl.offsetHeight ||
          (!scrollEl.scrollTop && touch.screenY > (lastTouch.screenY || 0)) ||
          (scrollEl.scrollTop === scrollEl.scrollHeight - scrollEl.offsetHeight && touch.screenY < (lastTouch.screenY || 0))
        ) {
          // 不能滚动的时候依然需要阻止滚动穿透
          e.cancelable && e.preventDefault();
        }

        lastTouch = touch;
      },
      false
    );
  }
};

export { scrollFix };
